package shuati.GUI;
import shuati.gui1.Cs;
import shuati.gui1.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GUITest {
    //// 定义一个名为DRIVER的常量，加载驱动
    public static final String DRIVER = "com.mysql.jdbc.Driver";
    // "test_gui"是指连接的数据库名，"localhost"是指主机地址，"3306"默认端口
    public static final String URL = "jdbc:mysql://localhost:3306/test_gui?useSSL=false";
    // MySQL用户名
    public static final String USER = "root";
    // 当前mysql密码
    public static final String PASSWORD = "8866";
    public JTextField usernameField;
    public JTextField phoneField;
    private JLabel timeText;
    private Connection connection = null;


    public static void main(String[] args) {
        new GUITest();
    }



    // 1.显示页面设计
    public GUITest() {
        //连接数据库

        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(URL, USER, PASSWORD);
            System.out.println("连接数据库...");
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }

        // 创建一个窗体
        JFrame frame = new JFrame("GUI 练习");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setLayout(new BorderLayout());
        //显示时间
        // 创建一个新的标签
        JLabel timeLabel = new JLabel();
        // 创建一个新的计时器
        Timer timer = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 当计时器触发时，更新标签的文本
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                SimpleDateFormat sdf1 = new SimpleDateFormat("HH");
                String shi = sdf1.format(new Date());
               int shijain = Integer.valueOf(shi);
                if ( shijain > 4 &&shijain < 12){
                    timeLabel.setText("上午好！" +sdf.format(new Date()));
                }else if( shijain < 15){
                    timeLabel.setText("中午好！"+sdf.format(new Date()));
                }else {
                    timeLabel.setText("晚上好！"+ sdf.format(new Date()));
                }

            }
        });
        // 启动计时器
        timer.start();
        timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
        frame.add(timeLabel, BorderLayout.NORTH);
        // 创建一个新的JPanel
        JPanel panel = new JPanel();
        // 设置JPanel的布局管理器为GridBagLayout
        panel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        // 设置组件的内边距
        gbc.insets = new Insets(7, 5, 7, 5);
        JLabel usernameLabel = new JLabel("用户名:");
        usernameField = new JTextField(20);
        JLabel phoneLabel = new JLabel("手机号:");
        phoneField = new JTextField(20);
        // 布局    18699162349
        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(usernameLabel, gbc);
        gbc.gridx = 1;
        gbc.gridy = 0;
        panel.add(usernameField, gbc);
        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(phoneLabel, gbc);
        gbc.gridx = 1;
        gbc.gridy = 1;
        panel.add(phoneField, gbc);

        frame.add(panel, BorderLayout.CENTER);
        // 创建一个新的JPanel
        JPanel buttonPanel = new JPanel();
        // 设置buttonPanel的布局管理器为FlowLayout
        buttonPanel.setLayout(new FlowLayout());
        // 创建两个新的按钮
        JButton writeButton = new JButton("写入");
        JButton confirmButton = new JButton("确认继续写入");
        // 将按钮添加到buttonPanel
        buttonPanel.add(writeButton);
        buttonPanel.add(confirmButton);
        frame.add(buttonPanel, BorderLayout.SOUTH);
        // 禁止用户调整窗口大小
        frame.setResizable(false);
        // 将窗口放置在屏幕的中心
        frame.setLocationRelativeTo(null);
        //添加按钮点击时需要执行的方法
        WriteButton writeButton1 = new WriteButton();
        writeButton.addActionListener(writeButton1);
        ConfirmButton confirmButton1 = new ConfirmButton();
        confirmButton.addActionListener(confirmButton1);
        frame.setVisible(true);
    }
    //连接数据库


    // 写入数据库
    public int xieRu(User user) {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DriverManager.getConnection(URL, USER, PASSWORD);
            System.out.println("连接成功");
            String sql = "INSERT INTO test (name, phone) VALUES (?, ?)";// sql语句，kk为数据库表名
            pstmt = con.prepareStatement(sql);// 对sql语句的预编译
            pstmt.setString(1, user.getName());// 设置sql语句中的第一个"?"为name属性
            pstmt.setString(2, user.getPhone());
            System.out.println("写人成功");
            int result = pstmt.executeUpdate();// 产生执行结果集
            if (result > 0) {
                return 1;
            } else {
                return 0;
            }
        } catch (Exception ee) {
            ee.printStackTrace();// 打印异常信息的位置
            return 0;
        }
    }

//    public int chaXun() {
//        Connection con = null;
//        PreparedStatement stmt = null;
//        // 创建一个新的SQL查询
//        String sql = "SELECT * FROM test WHERE name = uname ";
//
//        try {
//            // 执行查询
//            ResultSet rs = stmt.executeQuery(sql);
//            // 检查查询结果
//            if (rs.next()) {
//                System.out.println("用户名已存在");
//                return 1;
//            } else {
//                System.out.println("用户名不存在");
//                return 0;
//            }
//        } catch (SQLException e) {
//            throw new RuntimeException(e);
//        }
//
//    }

    //输入框判断
    public String[] panDuan() {
        String uname = usernameField.getText().trim();
        String uphone = phoneField.getText().trim();
        String[] str = new String[]{uname, uphone};
        String[] str1 = new String[]{""};
        if (uname.length() < 4) {
            JOptionPane.showMessageDialog(null, "姓名输入错误！！");// 弹窗提示
            return str1;
        } else if (uphone.length() != 11) {
            JOptionPane.showMessageDialog(null, "请输入11位手机号！！");// 弹窗提示
            return str1;
        } else {
            for (int i = 0; i < uphone.length(); i++) {
                // 手机号判断数字
                if (uphone.charAt(i) < '0' || uphone.charAt(i) > '9') {
                    JOptionPane.showMessageDialog(null, "手机号为数字,请重新输入");
                    return str1;
                }
            }
        }
        return str;
    }

    //按下写入是运行该函数
    public class WriteButton implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (panDuan().length > 1) {
                User user = new User();
                user.setName(panDuan()[0]);
                user.setPhone(panDuan()[1]);
                System.out.println(panDuan()[1]);
                if (!selectUser(user.getName())){
                int result = xieRu(user);
                if (result > 0) {
                    JOptionPane.showMessageDialog(null, "操作成功", "成功", JOptionPane.PLAIN_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(null, "操作失败");
                }}else {
                    JOptionPane.showMessageDialog(null, "用户已存在");
                }
            }
        }
    }

    public class ConfirmButton implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (panDuan().length > 1) {
                User user = new User();
                user.setName(panDuan()[0]);
                user.setPhone(panDuan()[1]);
                System.out.println(panDuan()[1]);

                if (!selectUser(user.getName())){
                    int result = xieRu(user);
                    if (result > 0) {
                        JOptionPane.showMessageDialog(null, "操作成功", "成功", JOptionPane.PLAIN_MESSAGE);
                        usernameField.setText("");
                        phoneField.setText("");
                    } else {
                        JOptionPane.showMessageDialog(null, "操作失败");
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "用户已存在！");
                }


            }
        }

    }


    public boolean selectUser(String userName){
        String sql = "SELECT name FROM test WHERE name = \""+userName+"\"";
        try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            System.out.println("查询："+rs.getRow());
            if (rs.next()){
                return true;
            } else {
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

}

/*
   抽象类Binary
    • toBin
    • toDec
    • toOct
    • toHex

    二进制类：Bin，继承Binary
    八进制类：Oct，继承Binary
    十进制类：Dec，继承Binary
    十六进制类：Hex，继承Binary


    // 1. 自己实现转换操作
    // 2. 使用JavaAPi


 */

